<template>
	<div>
		<el-table ref="multipleTable" :data="tableData" @selection-change="handleSelectionChange"
			@select-all="handleSelectAll" @select="handleSelect">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column prop="name" label="组织名称"></el-table-column>
		</el-table>

		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
			:page-sizes="[10, 20, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next"
			:total="total"></el-pagination>
		<div class="text-sm text-gray-600">
			当前已选择 <span class="font-medium text-primary">{{ selectedRows.length }}</span> 条数据，
			最大可选择 <span class="font-medium text-primary">{{ MAX_SELECTION }}</span> 条数据
		</div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			tableData: [],      // 当前页数据
			currentPage: 1,     // 当前页码
			pageSize: 10,       // 每页条数
			total: 0,          // 总数据量
			selectedRows: [],   // 所有已选数据（跨页累计）
			MAX_SELECTION: 7   // 最大选择数量
		};
	},
	methods: {
		handleSelectionChange() { },
		// 加载表格数据
		loadData() {
			const mockData = Array.from({ length: 50 }, (_, i) => ({
				id: i + 1,
				name: `组织 ${i + 1}`
			}));
			this.total = mockData.length;
			this.tableData = mockData.slice(
				(this.currentPage - 1) * this.pageSize,
				this.currentPage * this.pageSize
			);
		},

		// 单个选择变化
		handleSelect(selection, row) {
			// 获取当前操作是选中还是取消选中
			const isSelecting = selection.some(item => item.id === row.id);

			if (isSelecting) {
				// 如果是选中操作且将超过限制
				if (this.selectedRows.length >= this.MAX_SELECTION) {
					this.$message.error(`每次最多选择${this.MAX_SELECTION}个组织`);
					this.$refs.multipleTable.toggleRowSelection(row, false);
					return;
				}
				// 添加到已选列表
				this.selectedRows.push(row);
			} else {
				// 如果是取消选中，从已选列表中移除
				this.selectedRows = this.selectedRows.filter(item => item.id !== row.id);
			}

			// 同步当前页的选中状态
			this.syncSelectionState();
		},

		// 全选当前页
		handleSelectAll(selection) {
			const currentPageIds = this.tableData.map(item => item.id);

			// 先移除当前页的所有已选项
			this.selectedRows = this.selectedRows.filter(
				item => !currentPageIds.includes(item.id)
			);

			// 如果是全选操作
			if (selection.length > 0) {
				// 计算还能选择多少个
				const remaining = this.MAX_SELECTION - this.selectedRows.length;

				if (remaining <= 0) {
					this.$message.error(`每次最多选择${this.MAX_SELECTION}个组织`);
					this.syncSelectionState();
					return;
				}

				// 只添加不超过限制的数量
				const toAdd = selection.slice(0, remaining);
				this.selectedRows = [...this.selectedRows, ...toAdd];

				if (selection.length > remaining) {
					this.$message.error(`已自动选择${remaining}个，达到最大限制${this.MAX_SELECTION}个`);
				}
			}

			this.syncSelectionState();
		},

		// 同步当前页的选中状态
		syncSelectionState() {
			this.$nextTick(() => {
				if (!this.$refs.multipleTable) return;

				// 先清除当前页所有选中状态
				this.tableData.forEach(row => {
					this.$refs.multipleTable.toggleRowSelection(row, false);
				});

				// 然后重新设置当前页的选中状态
				this.tableData.forEach(row => {
					const isSelected = this.selectedRows.some(
						selected => selected.id === row.id
					);
					this.$refs.multipleTable.toggleRowSelection(row, isSelected);
				});
			});
		},

		// 分页变化处理
		handleSizeChange(val) {
			this.pageSize = val;
			this.currentPage = 1;
			this.loadData();
			this.syncSelectionState();
		},

		handleCurrentChange(val) {
			this.currentPage = val;
			this.loadData();
			this.syncSelectionState();
		},

		// 获取最终选择的ID数组
		getSelectedIds() {
			return this.selectedRows.map(row => row.id);
		}
	},
	mounted() {
		this.loadData();
	}
};
</script>